﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Diagnostics;
using System.Configuration;
using PRET.ReportDataDefine.DBData;

namespace PRET.PRETService.Data
{
    public class ServiceAdapter : IDisposable
    {
        private static WinCCDataProcess winccServer;
        private static SQLDataProcess sqlServer;
        private static WinCCDataProcess2 winccSQLServer;

        private EventLog log;
        public bool IsWinccConnected
        {
            get
            { return winccServer.IsConnected; }
        }
        //public bool IsSQLConnected
        //{
        //    get
        //    { return sqlServer.IsConnected; }
        //}

        public ServiceAdapter(EventLog log)
        {
            this.log = log;
            //InitializeWinccConnect();
            InitializeSQLConnect();
        }

        public void Dispose()
        {
            try
            {
                //this.winccServer.Dispose();
                sqlServer.Dispose();
                winccSQLServer.Dispose();
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.Dispose() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        private bool UsingAnalogData()
        {
            string usingAnalog = ConfigurationManager.ConnectionStrings["UsingAnalogData"].ConnectionString;
            if (usingAnalog == "0")
                return false;
            else
                return true;
        }

        /// <summary>
        /// 初始化WinCC数据库连接
        /// </summary>
        private void InitializeWinccConnect()
        {
            string servername = ConfigurationManager.ConnectionStrings["WinCCServerName"].ConnectionString;
            string dbname = ConfigurationManager.ConnectionStrings["WinCCDBName"].ConnectionString;
            string userid = ConfigurationManager.ConnectionStrings["WinCCUserID"].ConnectionString;
            string pwd = ConfigurationManager.ConnectionStrings["WinCCPassWord"].ConnectionString;
            winccServer = new WinCCDataProcess(servername, dbname, userid, pwd, this.log);
            //this.winccServer.TestConnectWinCC();
        }

        /// <summary>
        /// 初始化SQL数据库连接
        /// </summary>
        private void InitializeSQLConnect()
        {
            string servername = ConfigurationManager.ConnectionStrings["SQLServerName"].ConnectionString;
            string dbname = ConfigurationManager.ConnectionStrings["SQLCCDBName"].ConnectionString;
            string userid = ConfigurationManager.ConnectionStrings["SQLUserID"].ConnectionString;
            string pwd = ConfigurationManager.ConnectionStrings["SQLPassWord"].ConnectionString;
            if (sqlServer == null)
                sqlServer = new SQLDataProcess(servername, dbname, userid, pwd, this.log);
            if (winccSQLServer == null)
                winccSQLServer = new WinCCDataProcess2(servername, dbname, userid, pwd, this.log);
        }

        /// <summary>
        /// 创建所有表格
        /// </summary>
        public void CreateAllTablesInDB()
        {
            if(sqlServer == null)
            {
                throw new Exception("SQL适配器初始化失败!");
            }
            // 创建WinCC相关的SQL DB
            winccSQLServer.CreateWINCCSQLDB();
            // 创建System DB
            sqlServer.CreatePRETDB();
        }

        /// <summary>
        /// 收集最近时间段内的挤出机数据
        /// </summary>
        public void CollectionJCJData()
        {
            try
            {
                // 1. 取得最近一次收集挤出机数据的时间
                Dictionary<string, DateTime> latestTime = sqlServer.GetLatestJCJTime();
                foreach (KeyValuePair<string, DateTime> item in latestTime)
                {
                    string msg = string.Format("挤出机代号：{0}，上次收集时间：{1}", item.Key, item.Value);
                    //log.WriteEntry(msg);
                }

                // 2. 获取上次记录时间至现在的所有挤出机数据
                //List<JCJData> dataList = this.winccServer.GetJHJData(latestTime);
                List<JCJDataInfo> dataList = winccSQLServer.GetJCJDataFromDB(latestTime);

                // 3. 保存挤出机数据到SQL DB中
                foreach (JCJDataInfo item in dataList)
                {
                    sqlServer.AddJCJDataInfo(item);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionJCJData() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// 收集最近时间段的均化机数据
        /// </summary>
        public void CollectionJHJData()
        {
            try
            {
                // 1. 取得最近一次收集均化机数据的时间
                Dictionary<string, DateTime> latestTime = sqlServer.GetLatestJHJTime();

                // 2. 获取上次记录时间至现在的所有均化机数据
                JHJDataInfo dataInfo = winccSQLServer.GetJHJDataFromDB(latestTime);

                // 3. 保存均化机数据到SQL DB中
                if (dataInfo != null)
                    sqlServer.AddJHJInfo(dataInfo);
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionJHJData() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionWaitingOrder()
        {
            try
            {
                //List<WaitingOrder> dataList = this.winccServer.GetWaitingOrderList();
                List<WaitingOrder> dataList = winccSQLServer.GetWaitingOrderListFromDB();
                foreach (WaitingOrder item in dataList)
                    sqlServer.AddOrUpdateWaitingOrder(item);
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionWaitingOrder() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionTeamWorkTime()
        {
            try
            {
                // 1. 取得最近一次班组的工作时间
                Dictionary<string, DateTime> latestTime = sqlServer.GetLatestTeamWorkTime();
                // 2. 获得当前生产线上的班组工作时间列表
                List<TeamWorkTime> dataList = winccSQLServer.GetTeamWorkFromDB(latestTime);
                // 3. 保存班组工作时间数据到SQL DB中
                foreach (TeamWorkTime item in dataList)
                {
                    sqlServer.AddTeamWorkTime(item);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionTeamWorkTime() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionHighLowData()
        {
            try
            {
                // 1. 取得最近高低柜的记录时间
                Dictionary<string, DateTime> latestTime = sqlServer.GetLatestHighLowTime();
                // 2. 获得当前当前
                List<HighLowInfo> dataList = winccSQLServer.GetHighLowFromDB(latestTime);
                // 3. 保存班组工作时间数据到SQL DB中
                foreach (HighLowInfo item in dataList)
                {
                    sqlServer.AddHighLowInfo(item);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionTeamWorkTime() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionHighLowVoltage()
        {
            try
            {
                // 1. 取得最近高低柜的记录时间
                Dictionary<string, DateTime> latestTime = sqlServer.GetLatestHighLowVoltageTime();
                // 2. 获得当前当前
                List<HighLowVoltage> dataList = winccSQLServer.GetHighLowVoltageFromDB(latestTime);
                // 3. 保存班组工作时间数据到SQL DB中
                foreach (HighLowVoltage item in dataList)
                {
                    sqlServer.AddHighLowVoltage(item);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionTeamWorkTime() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionHumTemData()
        {
            try
            {
                // 1. 取得最近高低柜的记录时间
                DateTime latestTime = sqlServer.GetLatestHumTemTime();
                // 2. 获得当前当前
                List<HumidityTemperature> dataList = winccSQLServer.GetHumTemFromDB(latestTime);
                // 3. 保存班组工作时间数据到SQL DB中
                foreach (HumidityTemperature item in dataList)
                {
                    sqlServer.AddHumTem(item);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionTeamWorkTime() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionHSMLJData()
        {
            try
            {
                // 1. 取得滑石母粒机最近的记录时间
                DateTime latestTime = sqlServer.GetLatestHSMLJTime();
                // 2. 获得当前当前
                List<HSMLJInfo> dataList = winccSQLServer.GetHSMLJFromDB(latestTime);
                // 3. 保存班组工作时间数据到SQL DB中
                foreach (HSMLJInfo item in dataList)
                {
                    sqlServer.AddHSMLJ(item);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionHSMLJData() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionProlineEff()
        {
            try
            {
                sqlServer.CollectionProlineEff();
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionProlineEff() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void CollectionProduceTask()
        {
            try
            {
                sqlServer.CollectionProduceTask();
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionProduceTask() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
            
        }

        public void CollectionProlineStandby()
        {
            try
            {
                sqlServer.CollectionProlineStandby();
            }
            catch (Exception ex)
            {
                string msg = string.Format("ServiceAdapter.CollectionProlineStandby() Failed: {0}.\r\nDetail: {1}", ex.Message, ex.StackTrace);
                log.WriteEntry(msg, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void UpdateOrderFeedback()
        {
            sqlServer.UpdateOrderFeedBackTable();
        }

        public void DeleteOlderData()
        {
            winccSQLServer.DeleteOlderData();
        }
    }
}
